package com.indusfo.spc.service.impl;


import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.MaterialXOMapper;
import com.indusfo.spc.mapper.MtypeXOMapper;
import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.MaterialXOService;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.nio.cs.ext.MacArabic;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: IEIS2-COM
 * @Package: com.indusfo.spc.service.impl
 * @ClassName: MaterialXOServiceImpl
 * @Author: 熊冰
 * @Description: 物料业务层
 * @Date: 2019/8/19 10:23
 * @Version: 1.0
 */
@Service
public class MaterialXOServiceImpl implements MaterialXOService {
    private static final Logger logger = LoggerFactory.getLogger(MaterialXOServiceImpl.class);


    @Resource
    private MaterialXOMapper materialXOMapper;
    @Resource
    private MtypeXOMapper mtypeXOMapper;

    @Resource
    private UploadMapper uploadMapper;
    //查询
    /**
     * @author: louk
     * @param:
     * @Return:
     * @Description: :初始化页面默认显示树列表当中的第一个的信息
     * @date: 2019/9/4 17:21
     *
     */

    @Override
    public JSONObject listMaterialXO(MaterialXO materialXO) {

        try {

            // 获取一页显示多少行
            Integer pagesize = materialXO.getPagesize();
            // 获取查询第几页
            Integer pageindex = materialXO.getPageindex();
            Integer lMatType = materialXO.getlMatType();
            //初始值
            if(lMatType==null){
                MtypeXO mtypeXO=new MtypeXO();
                mtypeXO.setMtypePid(0);
                List<MtypeXO> mtypeXOS = mtypeXOMapper.selectAllMtypeXO(mtypeXO);
                if(mtypeXOS!=null && mtypeXOS.size()>0){
                    MtypeXO firstMtypexo = mtypeXOS.get(0);
                    Integer mtypeId = firstMtypexo.getMtypeId();
                    materialXO.setlMatType(mtypeId);
                }
            }else if(lMatType==0){
                materialXO.setlMatType(null);
            }

            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                materialXO.setIncept(pagesize * (pageindex - 1));
            }
            // 为空进行多条的分页查询
            // 调用Mapper分页查询方法

            List<MaterialXO> listForPage = materialXOMapper.selectAllMaterialXO(materialXO);
            // 判断是否查询到数据
            if (listForPage.isEmpty()) {
                return JSONObject.oK("没有相关数据",listForPage, 0);
            }
            // 查询有多少条数据条数
            if (pagesize != null && pageindex != null) {
                Integer count = materialXOMapper.countMaterialXO(materialXO);
                return JSONObject.oK(listForPage, count);
            }
            return JSONObject.oK(listForPage.get(0));



        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }

    }
    // 增加或修改
    @Override
    public JSONObject insertOrUpdateMaterialXO(MaterialXO materialXO) {
        try{
            /**
             * 新增编号名称不能重复
             */
            if(materialXO.getlDataState()==null){
                materialXO.setlDataState(1);
            }

            if (materialXO.getlMatId()!=null) {// 有id,做更新
                validate(materialXO);
                checkNoRepeat(materialXO);
                Integer row = materialXOMapper.updateByPrimaryKeySelective(materialXO);
                if(row == 0) {
                    throw new ModifyFailedException("更新物料失败！");
                }
                return JSONObject.oK("更新成功！", row);
            }else {// 没id,做新增
                // 校验传入参数
                validate(materialXO);
                checkNoRepeat(materialXO);

                Integer row = materialXOMapper.insertSelective(materialXO);
                if(row == 0) {
                    throw new ModifyFailedException("新增物料失败！");
                }
                return JSONObject.oK("新增成功！", row);
            }

        }catch (GlobalException e){
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }
    //删除
    @Override
    public JSONObject deleteMaterialXO(Long[] deteMaterialXO, Integer lDataState) {
        try {
            //1.校验
            if(deteMaterialXO == null) {
                throw new ParamsErrorException("控制项目id不能为空");
            }
            if(lDataState == null) {
                throw new ParamsErrorException("控制项目状态不能为空");
            }
            int row = materialXOMapper.deleteMaterialXO(deteMaterialXO,lDataState);
            String msg = "";
            switch (lDataState) {
                case 1:
                    msg = "启用";
                    break;
                case 2:
                    msg = "删除";
                    break;
                case 3:
                    msg = "停用";
            }

            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (lDataState) {
                    case 1:
                        throw new ModifyFailedException(msg+"失败!");
                    case 2:
                        throw new ModifyFailedException(msg+"失败!");
                    case 3:
                        throw new ModifyFailedException(msg+"失败!");
                }
            }
            return JSONObject.oK(msg+"成功！", row);
        }catch (GlobalException e){
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    @Override
    public JSONObject advancedQuery(MaterialXO materialXO) {


        try {

            // 获取一页显示多少行
            Integer pagesize = materialXO.getPagesize();
            // 获取查询第几页
            Integer pageindex = materialXO.getPageindex();
            Integer lMatType = materialXO.getlMatType();

            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                materialXO.setIncept(pagesize * (pageindex - 1));
            }
            List<MaterialXO> materialXOS = materialXOMapper.advancedQuery(materialXO);

            // 判断是否查询到数据
            if (materialXOS.isEmpty()) {
                return JSONObject.oK("没有相关数据",materialXOS, 0);
            }
            // 查询有多少条数据条数
            if (pagesize != null && pageindex != null) {
                Integer count= materialXOMapper.countMaterialXO(materialXO);
                return JSONObject.oK(materialXOS, count);
            }
            return JSONObject.oK(materialXOS.get(0));



        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }

    }


    //验证重复
    private JSONObject checkParamsNotRepeat(MaterialXO materialXO) {
        try {
            // 判断不良原因类型ID是否传入
            if (materialXO.getlMatId() == null || materialXO.getlMatId() == 0) {
                throw new ParamsErrorException("未传入物料ID");
            } else {
                MaterialXO check = new MaterialXO();
                check.setVcProjectName(materialXO.getVcProjectName());
                if (materialXO.getlMatId() != null) {
                    // 有SOP基础资料ID为更新操作,调用剔除本条记录是否有重复
                    check.setlMatId(materialXO.getlMatId());
                    int row = materialXOMapper.countParamsNotRepeat(check);
                    if (row > 0) {
                        throw new ParamsErrorException("已存在该产品!");
                    }
                } else {
                    // 无SOP基础资料ID为新增操作,调用Mapper查询所有是否有重复
                    int row = materialXOMapper.countParamsNotRepeat(check);
                    if (row > 0) {
                        throw new ParamsErrorException("已存在该产品!");
                    }
                }
                return JSONObject.oK();
            }
        } catch (GlobalException e) {
            // 捕获异常,打印并返回
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    //判断物料编码物料名称是否重复
    private void checkNoRepeat(MaterialXO materialXO){
        int codeRow = materialXOMapper.countCodeNoRepeat(materialXO);
        if(codeRow>0){
            throw new ParamsErrorException("物料编码已存在");
        }
        int nameRow = materialXOMapper.countNameNoRepeat(materialXO);
        if(nameRow>0){
            throw new ParamsErrorException("物料名称已存在");
        }
    }
    //非空判断
    private void validate(MaterialXO materialXO) {
        //物料编码
        String vcMatCode=materialXO.getVcMatCode();
        //物料名称
        String vcProjectName =materialXO.getVcProjectName();
        //规格型号
        String vcModel =materialXO.getVcModel();
        //条码规则
        Integer vcBarrule =materialXO.getVcBarrule();
        if(StringUtils.isEmpty(vcMatCode)){
            throw new ParamsErrorException("物料编码不能为空");
        }
        if(StringUtils.isEmpty(vcProjectName)){
            throw new ParamsErrorException("物料名称不能为空");
        }
        if(StringUtils.isEmpty(vcModel)){
            throw new ParamsErrorException("规格型号不能为空");
        }
        if(vcBarrule==null){
            throw new ParamsErrorException("条码规则不能为空");
        }
        //物料单位
        Integer lMatUnit = materialXO.getlMatUnit();
        //物料类型
        Integer lMatType = materialXO.getlMatType();
        //物料来源
        Integer lSourceId = materialXO.getlSourceId();
        if(lMatUnit == null){
            throw new ParamsErrorException("物料单位不能为空");
        }
        if(lMatType == null){
            throw new ParamsErrorException("物料类型不能为空");
        }
        if(lSourceId == null){
            throw new ParamsErrorException("物料来源不能为空");
        }

    }
    @Override
    public String checkExcelContent(MaterialXO materialXO){
        //物料编码
        String vcMatCode=materialXO.getVcMatCode();
        //物料名称
        String vcProjectName =materialXO.getVcProjectName();
        //规格型号
        String vcModel =materialXO.getVcModel();
        //条码规则
        String ruleName =materialXO.getRule();
        //物料名称
        String mtype = materialXO.getMtype();
        //单位名称
        String matunit = materialXO.getMatunit();
        //物料来源
        String lSourceName = materialXO.getlSourceName();
        //版本号
        String versionNumber =materialXO.getVersionNumber();
        //图号
        String figureNumber = materialXO.getFigureNumber();
        //客户代码
        String customerCode =materialXO.getCustomerCode();
        //单位数量
        Integer lMatUnitCount=materialXO.getlMatUnitCount();
        //成品机型
        String finishedProductModeltCount =materialXO.getFinishedProductModel();
        //资源数
        Integer resourceNumber=materialXO.getResourceNumber();
        //生产节拍
        Integer productionTakt=materialXO.getProductionTakt();;
        //干燥时间
        Integer dryingTime=materialXO.getDryingTime();
        //保有量
        Integer inventory=materialXO.getInventory();
        //报工数量
        Integer workNumber=materialXO.getWorkNumber();
        if(StringUtils.isBlank(vcMatCode) && StringUtils.isBlank(vcProjectName) && StringUtils.isBlank(vcModel) && StringUtils.isBlank(ruleName) &&
                StringUtils.isBlank(mtype) && StringUtils.isBlank(matunit) && StringUtils.isBlank(lSourceName) &&
                StringUtils.isBlank(versionNumber) && StringUtils.isBlank(figureNumber) && StringUtils.isBlank(finishedProductModeltCount) &&
                StringUtils.isBlank(customerCode) && StringUtils.isBlank(lMatUnitCount.toString()) && StringUtils.isBlank(resourceNumber.toString()) &&
                StringUtils.isBlank(productionTakt.toString()) && StringUtils.isBlank(dryingTime.toString()) &&
                StringUtils.isBlank(inventory.toString()) && StringUtils.isBlank(workNumber.toString())){
            return "";
        }
        if(StringUtils.isEmpty(vcMatCode)){
            return "物料编码不能为空";
        }
        if(StringUtils.isEmpty(vcProjectName)){
            return "物料名称不能为空";
        }
        if(StringUtils.isEmpty(vcModel)){
            return "规格型号不能为空";
        }
        if(StringUtils.isEmpty(ruleName)){
            return "条码规则不能为空";
        }
        //获取到条码规则的信息
        Map<String, Rule> ruleMap = uploadMapper.queryRule();
        if(!ruleMap.containsKey(ruleName)){
            return "条码规则名称书写不规范/不存在";
        }else{
            Rule rule = ruleMap.get(ruleName);
            materialXO.setVcBarrule(
                    rule.getRuleId()
            );
        }

        if(StringUtils.isEmpty(matunit)){
            return "单位名称不能为空";
        }
        //获取到单位的信息
        Map<String, Datadict> matunitMap = uploadMapper.queryType(101003);
        if(!matunitMap.containsKey(matunit)){
            return "单位名称书写不规范/不存在";
        }else{
            Datadict tdatadict = matunitMap.get(matunit);
            materialXO.setlMatUnit(tdatadict.getItemId());
        }

        if(StringUtils.isEmpty(mtype)){
            return "物料类别名称不能为空";
        }
        //物料类别信息
        Map<String, MtypeXO> mtypeMap = uploadMapper.queryMtype();
        if(!mtypeMap.containsKey(mtype)){
            return "物料类别名称书写不规范/不存在";
        }else{
            MtypeXO mType = mtypeMap.get(mtype);
            materialXO.setlMatType(mType.getMtypeId());
        }

        if(StringUtils.isEmpty(lSourceName)){
            return "物料来源名称不能为空";
        }
        //物料类别信息
        Map<String, Datadict> lSourceMap = uploadMapper.queryType(101033);
        if(!lSourceMap.containsKey(lSourceName)){
            return "物料来源名称书写不规范/不存在";
        }else{
            Datadict tdatadict = lSourceMap.get(lSourceName);
            materialXO.setlSourceId(tdatadict.getItemId());
        }
        int codeRow = materialXOMapper.countCodeNoRepeat(materialXO);
        if(codeRow>0){
             return "物料编码已存在";
        }
        int nameRow = materialXOMapper.countNameNoRepeat(materialXO);
        if(nameRow>0){
            return "物料名称已存在";
        }
        return null;
    }
}
